/**
 * 工时相关的自定义 Hook
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { message } from 'antd';
import { pingCodeAPI } from '../utils/pingcodeApi';
import type {
  Workload,
  WorkloadType,
  WorkloadQueryParams,
} from '../types/workload';
import type { User, Project } from '../types/workItem';

// 添加工时统计类型定义
export interface WorkloadStatistics {
  totalDuration: number; // 总工时
  projectStats: Array<{
    projectId: string;
    projectName: string;
    totalDuration: number;
  }>;
  userStats: Array<{
    userId: string;
    userName: string;
    totalDuration: number;
  }>;
  typeStats: Array<{
    typeId: string;
    typeName: string;
    totalDuration: number;
  }>;
}

export function useWorkloads(initialParams?: WorkloadQueryParams) {
  const [workloads, setWorkloads] = useState<Workload[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState<string | null>(null);

  // 计算工时统计信息
  const statistics = useMemo((): WorkloadStatistics => {
    if (!workloads || workloads.length === 0) {
      return {
        totalDuration: 0,
        projectStats: [],
        userStats: [],
        typeStats: [],
      };
    }

    // 计算总工时
    const totalDuration = workloads.reduce((sum, workload) => sum + workload.duration, 0);

    // 按项目统计工时（这里使用principal信息作为项目信息）
    const projectMap = new Map<string, { name: string; duration: number }>();
    workloads.forEach(workload => {
      if (workload.principal && workload.principal.id) {
        const projectKey = workload.principal.id;
        const projectName = workload.principal.title || '未知项目';
        
        if (projectMap.has(projectKey)) {
          projectMap.get(projectKey)!.duration += workload.duration;
        } else {
          projectMap.set(projectKey, { name: projectName, duration: workload.duration });
        }
      }
    });

    const projectStats = Array.from(projectMap.entries()).map(([projectId, data]) => ({
      projectId,
      projectName: data.name,
      totalDuration: data.duration,
    }));

    // 按登记人统计工时
    const userMap = new Map<string, { name: string; duration: number }>();
    workloads.forEach(workload => {
      const userId = workload.report_by.id;
      const userName = workload.report_by.display_name || workload.report_by.name;
      
      if (userMap.has(userId)) {
        userMap.get(userId)!.duration += workload.duration;
      } else {
        userMap.set(userId, { name: userName, duration: workload.duration });
      }
    });

    const userStats = Array.from(userMap.entries()).map(([userId, data]) => ({
      userId,
      userName: data.name,
      totalDuration: data.duration,
    }));

    // 按工时类型统计
    const typeMap = new Map<string, { name: string; duration: number }>();
    workloads.forEach(workload => {
      const typeId = workload.type.id;
      const typeName = workload.type.name;
      
      if (typeMap.has(typeId)) {
        typeMap.get(typeId)!.duration += workload.duration;
      } else {
        typeMap.set(typeId, { name: typeName, duration: workload.duration });
      }
    });

    const typeStats = Array.from(typeMap.entries()).map(([typeId, data]) => ({
      typeId,
      typeName: data.name,
      totalDuration: data.duration,
    }));

    return {
      totalDuration,
      projectStats,
      userStats,
      typeStats,
    };
  }, [workloads]);

  const fetchWorkloads = useCallback(async (params?: WorkloadQueryParams) => {
    console.log('开始获取工时列表:', params);
    setLoading(true);
    setError(null);

    try {
      // 如果没有指定分页参数，获取所有数据
      if (!params?.page_index && !params?.page_size) {
        console.log('获取所有工时数据');
        const allWorkloads: any[] = [];
        let currentPage = 0;
        const pageSize = 100; // 每次获取100条
        let totalCount = 0;

        while (true) {
          const queryParams = {
            ...params,
            page_index: currentPage,
            page_size: pageSize,
          };

          const response = await pingCodeAPI.getWorkloads(queryParams);
          console.log(`获取第${currentPage + 1}页工时数据:`, {
            count: response.values?.length || 0,
            total: response.total
          });

          if (response.values && response.values.length > 0) {
            allWorkloads.push(...response.values);
            totalCount = response.total || 0;

            // 如果获取的数据少于页面大小，说明已经是最后一页
            if (response.values.length < pageSize) {
              break;
            }

            currentPage++;
          } else {
            totalCount = response.total || 0;
            break;
          }
        }

        console.log(`获取工时列表完成，共 ${allWorkloads.length} 条记录，总计: ${totalCount}`);
        setWorkloads(allWorkloads);
        setTotal(totalCount);

        if (allWorkloads.length === 0 && totalCount === 0) {
          message.info('暂无工时数据，请尝试调整查询条件');
        } else if (allWorkloads.length > 0) {
          message.success(`查询成功，共找到 ${allWorkloads.length} 条工时记录`);
        }
      } else {
        // 有分页参数时，按分页获取
        const response = await pingCodeAPI.getWorkloads(params);
        console.log('获取工时列表成功:', response);
        setWorkloads(response.values || []);
        setTotal(response.total || 0);

        if (response.message) {
          message.warning(response.message);
        } else if (response.values && response.values.length === 0 && response.total === 0) {
          message.info('暂无工时数据，请尝试调整查询条件');
        }
      }
    } catch (err) {
      console.error('获取工时列表失败:', err);
      const errorMessage = err instanceof Error ? err.message : '获取工时列表失败';
      setError(errorMessage);
      message.error(errorMessage);
      setWorkloads([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (initialParams) {
      fetchWorkloads(initialParams);
    }
  }, [fetchWorkloads, initialParams]);

  return {
    workloads,
    loading,
    total,
    error,
    statistics, // 新增统计信息
    fetchWorkloads,
    refetch: () => fetchWorkloads(initialParams),
  };
}

export function useWorkloadMeta() {
  const [workloadTypes, setWorkloadTypes] = useState<WorkloadType[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchAllUsers = useCallback(async () => {
    const allUsers: User[] = [];

    try {
      console.log('获取全局用户列表');
      let pageIndex = 1;
      const pageSize = 100;

      while (true) {
        const response = await pingCodeAPI.getUsers({
          page_size: pageSize,
          page_index: pageIndex
        });

        if (response.values && response.values.length > 0) {
          allUsers.push(...response.values);

          if (response.values.length < pageSize) {
            break;
          }

          pageIndex++;
        } else {
          break;
        }
      }

      console.log(`获取到全局用户 ${allUsers.length} 个用户`);

      // 去重，以用户ID为准
      const uniqueUsers = allUsers.reduce((acc, user) => {
        if (!acc.find(u => u.id === user.id)) {
          acc.push(user);
        }
        return acc;
      }, [] as User[]);

      console.log(`去重后共 ${uniqueUsers.length} 个用户`);
      return uniqueUsers;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      return [];
    }
  }, []);

  const fetchProjects = useCallback(async () => {
    const allProjects: Project[] = [];

    try {
      console.log('获取全部项目列表');
      let pageIndex = 1;
      const pageSize = 100;

      while (true) {
        const response = await pingCodeAPI.getProjects({
          page_size: pageSize,
          page_index: pageIndex
        });

        if (response.values && response.values.length > 0) {
          allProjects.push(...response.values);

          // 如果获取的数据少于批次大小，说明已经是最后一页
          if (response.values.length < pageSize) {
            break;
          }

          pageIndex++;
        } else {
          break;
        }
      }

      console.log(`获取到全部项目 ${allProjects.length} 个项目`);

      // 去重，以项目ID为准
      const uniqueProjects = allProjects.reduce((acc, project) => {
        if (!acc.find(p => p.id === project.id)) {
          acc.push(project);
        }
        return acc;
      }, [] as Project[]);

      console.log(`去重后共 ${uniqueProjects.length} 个项目`);
      return uniqueProjects;
    } catch (error) {
      console.error('获取项目列表失败:', error);
      return [];
    }
  }, []);

  const fetchMeta = useCallback(async () => {
    setLoading(true);

    try {
      const [typesData, usersData, projectsData] = await Promise.allSettled([
        pingCodeAPI.getWorkloadTypes(),
        fetchAllUsers(),
        fetchProjects(),
      ]);

      if (typesData.status === 'fulfilled') {
        setWorkloadTypes(typesData.value);
      }

      if (usersData.status === 'fulfilled') {
        setUsers(usersData.value);
      }

      if (projectsData.status === 'fulfilled') {
        setProjects(projectsData.value);
      }
    } catch (err) {
      console.error('获取工时元数据失败:', err);
    } finally {
      setLoading(false);
    }
  }, [fetchAllUsers, fetchProjects]);

  useEffect(() => {
    fetchMeta();
  }, [fetchMeta]);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const usersData = await fetchAllUsers();
      setUsers(usersData);
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, [fetchAllUsers]);

  const fetchWorkloadTypes = useCallback(async () => {
    setLoading(true);
    try {
      const typesData = await pingCodeAPI.getWorkloadTypes();
      setWorkloadTypes(typesData);
    } catch (error) {
      console.error('获取工时类型失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchProjectsWrapper = useCallback(async () => {
    setLoading(true);
    try {
      const projectsData = await fetchProjects();
      setProjects(projectsData);
    } catch (error) {
      console.error('获取项目列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, [fetchProjects]);

  return {
    workloadTypes,
    users,
    projects,
    loading,
    refetch: fetchMeta,
    fetchProjects: fetchProjectsWrapper,
    fetchUsers,
    fetchWorkloadTypes,
  };
}